<?php

namespace admin\listener;

use herosphp\bean\Beans;
use herosphp\http\HttpRequest;
use herosphp\listener\IWebAplicationListener;
use herosphp\listener\WebApplicationListenerMatcher;
use herosphp\string\StringUtils;
use herosphp\utils\AjaxResult;
use herosphp\web\WebUtils;

/**
 * 后台操作权限生命周期监听器
 * @package admin\listener
 * @author yangjian102621@gmail.com
 */
 class OperationPermissionListener extends WebApplicationListenerMatcher implements IWebAplicationListener {

     /**
      * action 方法调用之前
      * @return mixed
      */
     public function beforeActionInvoke(HttpRequest $request)
     {
         //捕获操作，并插入数据库
//         $module = $request->getModule();
//         $action = $request->getAction();
//         $method = $request->getMethod();
//         $opt = "{$module}/{$action}/{$method}";
//         $operationService = Beans::get('system.operation.service');
//         if ( $operationService->count(array('optkey'=> $opt)) == 0 ) {
//             $data = array(
//                 'name' => $opt,
//                 'optkey' => $opt,
//                 'addtime' => date('Y-m-d H:i:s'),
//                 'updatetime' => date('Y-m-d H:i:s'),
//             );
//             $operationService->add($data);
//         }

     }


     //记录后台的操作日志
     public function actionInvokeFinally(HttpRequest $request, $actionInstance)
     {
         if ( $request->getModule() != 'admin' ) return false; //只记录后台的操作

         if ( $request->getAction() == 'login' ) return false; //登陆日志单独记录

         //判断请求的类型,不是ajax操作的就不记录操作日志
         if ( strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest' ) {
             return false;
         }

         //获取操作状态看看是否操作成功, 操作成功才记录日志
         $content = ob_get_contents();
         $result = StringUtils::jsonDecode($content);

         $message = $request->getParameter('logmessage');
         /*
         if ( $message && $result['code'] == AjaxResult::OP_SUCCESS ) {
             $sysLogService = Beans::get('system.systemOptLog.service');
             $managerService = Beans::get('admin.manager.service');
             $manager = $managerService->getLoginManager();
             $sysLogService->add(array(
                 'opt_id' => $manager['id'],
                 'opt_name' => $manager['name'],
                 'action' => $request->getAction(),
                 'method' => $request->getMethod(),
                 'content' => $message,
                 'addtime' => date('Y-m-d H:i:s'),
                 'ip' => WebUtils::getClientIP()
             ));
         }*/
     }

     public function beforeSendResponse(HttpRequest $request, $actionInstance)
     {
         //加载系统配置
         $service = Beans::get('system.setting.service');
         $settings = $service->getSettings();
         $actionInstance->assign('__settings', $settings);
     }

 }
